<template>
	<view class="store-detail-page">
		<!-- 店铺头部信息 -->
		<view class="store-header" v-if="storeId > 0">
			<view class="back-icon" @click="goBack">
				<text class="iconfont">←</text>
			</view>
			<image :src="handleImgURL(storeInfo.storeLogo)" mode="aspectFill" class="store-header-img" lazy-load
				@error="handleImgError($event, 'logo')"></image>
			<view class="store-header-info">
				<text class="store-header-name">{{ storeInfo.storeName || '未知店铺' }}</text>
				<view class="store-header-meta">
					<view class="rating-wrap" v-if="storeInfo.rating || storeInfo.rating === 0">
						<text class="iconfont star-icon">★</text>
						<text class="rating-value">{{ storeInfo.rating.toFixed(1) }}</text>
					</view>
					<text class="delivery-time" v-if="storeInfo.deliveryTime">{{ storeInfo.deliveryTime }}分钟</text>
					<text class="min-price"
						v-if="storeInfo.minOrderPrice || storeInfo.minOrderPrice === 0">起送¥{{ storeInfo.minOrderPrice }}</text>
				</view>
				<view class="storeStatus-badge" :class="storeInfo.storeStatus === 1 ? 'open' : 'close'">
					{{ storeInfo.storeStatus === 1 ? '营业中' : '休息中' }}
				</view>
			</view>
			<!-- 购物车入口 -->
			<view class="cart-entrance" @click="goToCart">
				<text class="iconfont">🛒</text>
				<view class="cart-count" v-if="totalCartCount > 0">{{ totalCartCount }}</view>
			</view>
		</view>

		<!-- 搜索栏 -->
		<view class="search-box" v-if="storeId > 0">
			<text class="iconfont search-icon">🔍</text>
			<input type="text" placeholder="搜索店铺内商品" v-model="searchKey" @input="handleSearch"
				@confirm="handleSearchConfirm" class="search-input" />
			<text v-if="searchKey" class="iconfont clear-icon" @click="clearSearch">×</text>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar" v-if="storeId > 0">
			<view class="filter-item" @click="toggleSort">
				<text class="filter-text">{{ currentSortText }}</text>
				<text class="iconfont">▼</text>
			</view>
			<view class="filter-item" @click="toggleCategory">
				<text class="filter-text">商品分类</text>
				<text class="iconfont">▼</text>
			</view>
		</view>

		<!-- 错误提示 -->
		<view v-if="errorMsg" class="error-container">
			<text class="iconfont error-icon">⚠️</text>
			<text class="error-text">{{ errorMsg }}</text>
			<button class="retry-btn" @click="reloadAll">重新加载</button>
		</view>

		<!-- 加载中状态（Uniapp原生自定义加载） -->
		<view v-if="loading && !errorMsg" class="loading-container">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list" v-if="storeId > 0 && !loading && !errorMsg">
			<view class="goods-card" v-for="goods in goodsList" :key="`goods_${goods.goodsId}`"
				:class="{ 'goods-offline': goods.isOnSale === 0 }" @click="goToGoodsDetail(goods)">
				<image :src="handleImgURL(goods.goodsImg)" mode="aspectFill" class="goods-img" lazy-load
					@error="handleImgError($event, 'goods')"></image>
				<view class="offline-tag" v-if="goods.isOnSale === 0">已下架</view>
				<view class="goods-info">
					<view class="goods-name-wrap">
						<text class="goods-name">{{ goods.goodsName || '未知商品' }}</text>
					</view>

					<view class="goods-middle-wrap">
						<text class="goods-spec" v-if="goods.categoryName">{{ goods.categoryName }}</text>
						<view class="cart-operation" v-if="goods.isOnSale !== 0 && storeInfo.storeStatus === 1">
							<text class="iconfont minus-icon" @click.stop="decreaseCount(goods)"
								:class="{ 'disabled': getGoodsCount(goods) <= 1 }">-</text>
							<text class="count" v-if="getGoodsCount(goods) > 0">{{ getGoodsCount(goods) }}</text>
							<button class="add-btn" @click.stop="addToCart(goods)">
								<text class="iconfont">+</text>
							</button>
						</view>
					</view>

					<view class="goods-price-wrap">
						<text class="goods-price">¥{{ (goods.goodsPrice || 0).toFixed(2) }}</text>
						<text class="goods-sales" v-if="goods.salesNum">销量{{ goods.salesNum }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 无数据状态 -->
		<view class="no-data" v-if="storeId > 0 && !loading && !errorMsg && goodsList.length === 0">
			<text class="iconfont empty-icon">📭</text>
			<text class="no-data-text">暂无商品</text>
			<text class="no-data-subtext">店铺正在备货中~</text>
		</view>
	</view>
</template>

<script>
	import {
		getStore
	} from '@/api/store.js'
	import {
		queryPage
	} from '@/api/goods.js'
	import {
		getCategoryNamesByStoreId
	} from '@/api/category.js'
	// 导入购物车API
	import {
		addCart,
	} from '@/api/cart.js'
	import {
		baseUrl
	} from '@/utils/config.js'

	export default {
		data() {
			return {
				storeId: 0,
				storeInfo: {},
				goodsList: [],
				loading: false,
				errorMsg: '',
				searchKey: '',
				pageNum: 1,
				pageSize: 10,
				hasMore: true,
				searchTimer: null,
				currentSort: 'sales_num DESC',
				currentSortText: '销量优先',
				currentCategory: '',
				categoryList: [],
				// 本地购物车状态，用于临时存储和展示
				localCartMap: {}
			}
		},
		computed: {
			// 计算当前店铺的购物车总数量
			totalCartCount() {
				return Object.values(this.localCartMap).reduce((total, item) => {
					return item.storeId === this.storeId ? total + item.count : total
				}, 0)
			}
		},
		onLoad(options) {
			// 安全获取storeId
			this.storeId = options?.storeId ? Number(options.storeId) : 0;
			if (!this.storeId) {
				this.errorMsg = '无效的店铺信息';
				return;
			}
			this.localCartMap = {};
			this.reloadAll();
			// 监听购物车变化事件，同步本地状态
			uni.$on('cartCountChange', this.syncCartStatus);
		},
		onUnload() {
			// 移除事件监听
			uni.$off('cartCountChange', this.syncCartStatus);
		},
		onReachBottom() {
			if (this.hasMore && !this.loading && !this.errorMsg && this.storeId > 0) {
				this.pageNum++;
				this.getGoodsList();
			}
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1,
					fail: () => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				});
			},
			handleImgURL(url) {
				if (!url) return '/static/images/default-goods.png';
				return url.includes('http') ? url : `${baseUrl}${url}`;
			},
			handleImgError(e, type) {
				if (!e?.target) return;
				if (type === 'logo') {
					e.target.src = '/static/images/default-store.png';
				} else {
					e.target.src = '/static/images/default-goods.png';
				}
			},
			reloadAll() {
				if (!this.storeId) return;
				this.errorMsg = '';
				// 并行加载数据
				Promise.all([
					this.getStoreDetail(),
					this.getStoreCategoryList()
				]).then(() => {
					this.pageNum = 1;
					this.getGoodsList();
				}).catch(err => {
					console.error('数据加载失败:', err);
					this.errorMsg = '数据加载失败，请重试';
				});
			},
			async getStoreDetail() {
				try {
					const res = await getStore(this.storeId);
					if (!res) throw new Error('获取店铺信息无响应');
					if ([200, 0].includes(res?.code) && res?.data) {
						this.storeInfo = res.data || {};
					} else {
						throw new Error(res?.msg || '获取店铺信息失败');
					}
				} catch (err) {
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
					throw err;
				}
			},
			async getGoodsList() {
				if (!this.storeId) return;
				this.loading = true;

				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						storeId: this.storeId,
						keyword: this.searchKey || undefined,
						orderBy: this.currentSort,
						categoryName: this.currentCategory || undefined
					};

					const res = await queryPage(params);

					if (!res) {
						throw new Error('获取商品列表失败：服务器未返回数据');
					}

					if ([200, 0].includes(res.code) && res.data) {
						const goodsArray = res.data.list || [];
						const formatData = goodsArray.map(goods => ({
							...goods,
							goodsPrice: Number(goods.goodsPrice) || 0,
							salesNum: Number(goods.salesNum) || 0,
							isOnSale: goods.isOnSale ?? 1,
							goodsId: goods.goodsId || Date.now()
						}));

						this.goodsList = this.pageNum === 1 ? formatData : [...this.goodsList, ...formatData];
						this.hasMore = this.goodsList.length < (res.data.total || 0);
					} else {
						throw new Error(res?.msg || `获取商品列表失败，错误码: ${res?.code}`);
					}
				} catch (err) {
					this.errorMsg = err.message;
					if (this.pageNum === 1) this.goodsList = [];
				} finally {
					this.loading = false;
				}
			},
			async getStoreCategoryList() {
				try {
					const res = await getCategoryNamesByStoreId(this.storeId);
					if (!res) throw new Error('分类接口无响应');
					if ([200, 0].includes(res.code) && Array.isArray(res.data)) {
						this.categoryList = ['全部分类', ...res.data];
					} else {
						this.categoryList = ['全部分类'];
					}
				} catch (err) {
					console.error('获取店铺分类失败：', err);
					this.categoryList = ['全部分类'];
				}
			},
			handleSearch() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.pageNum = 1;
					this.getGoodsList();
				}, 500);
			},
			handleSearchConfirm() {
				clearTimeout(this.searchTimer);
				this.pageNum = 1;
				this.getGoodsList();
			},
			clearSearch() {
				this.searchKey = '';
				clearTimeout(this.searchTimer);
				this.pageNum = 1;
				this.getGoodsList();
			},
			toggleSort() {
				const sortMap = {
					'sales_num DESC': {
						text: '价格从低到高',
						value: 'price ASC'
					},
					'price ASC': {
						text: '价格从高到低',
						value: 'price DESC'
					},
					'price DESC': {
						text: '销量优先',
						value: 'sales_num DESC'
					}
				};
				const nextSort = sortMap[this.currentSort];
				if (nextSort) {
					this.currentSort = nextSort.value;
					this.currentSortText = nextSort.text;
					this.pageNum = 1;
					this.getGoodsList();
				}
			},
			toggleCategory() {
				if (this.categoryList.length === 0) {
					this.categoryList = ['全部分类'];
				}
				uni.showActionSheet({
					itemList: this.categoryList,
					success: (res) => {
						this.currentCategory = res.tapIndex === 0 ? '' : this.categoryList[res.tapIndex];
						this.pageNum = 1;
						this.getGoodsList();
					},
					fail: (err) => {
						console.error('选择分类失败:', err);
					}
				});
			},
			// 获取商品在购物车中的数量
			getGoodsCount(goods) {
				if (!goods?.goodsId) return 0;
				return this.localCartMap[goods.goodsId]?.count || 0;
			},
			// 加入购物车（调用后端API）
			async addToCart(goods) {
				if (!goods?.goodsId) {
					uni.showToast({
						title: '商品信息错误',
						icon: 'none'
					});
					return;
				}
				if (goods.isOnSale === 0) {
					uni.showToast({
						title: '商品已下架',
						icon: 'none'
					});
					return;
				}
				if (this.storeInfo.storeStatus !== 1) {
					uni.showToast({
						title: '店铺已休息',
						icon: 'none'
					});
					return;
				}

				const goodsId = goods.goodsId;
				const currentCount = this.getGoodsCount(goods);

				if (currentCount >= 99) {
					uni.showToast({
						title: '商品数量上限为99',
						icon: 'none'
					});
					return;
				}

				const targetCount = currentCount + 1;

				try {
					// 调用后端API添加/更新购物车
					const res = await addCart({
						goodsId: goodsId,
						count: targetCount,
						storeId: this.storeId
					});

					if ([200, 0].includes(res.code)) {
						// 更新本地购物车状态
						if (currentCount === 0) {
							this.$set(this.localCartMap, goodsId, {
								goodsId: goods.goodsId,
								goodsName: goods.goodsName,
								goodsImg: goods.goodsImg,
								goodsPrice: goods.goodsPrice,
								count: targetCount,
								storeId: this.storeId,
								storeName: this.storeInfo.storeName || '未知店铺',
								selected: true
							});
						} else {
							this.$set(this.localCartMap[goodsId], 'count', targetCount);
						}

						// 触发购物车数量变化事件
						uni.$emit('cartCountChange');

						uni.showToast({
							title: '已加入购物车',
							icon: 'success',
							duration: 1000
						});
					} else {
						throw new Error(res.msg || '加入购物车失败');
					}
				} catch (e) {
					console.error('加入购物车失败：', e);
					uni.showToast({
						title: e.message || '加入购物车失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			// 减少购物车数量（调用后端API）
			async decreaseCount(goods) {
				if (!goods?.goodsId) return;

				const goodsId = goods.goodsId;
				const currentCount = this.getGoodsCount(goods);

				if (currentCount <= 0) return;

				try {
					if (currentCount === 1) {
						// 数量为1时，删除购物车商品
						const res = await deleteCart({
							goodsId: goodsId,
							storeId: this.storeId
						});

						if ([200, 0].includes(res.code)) {
							this.$delete(this.localCartMap, goodsId);
						} else {
							throw new Error(res.msg || '删除购物车商品失败');
						}
					} else {
						// 数量大于1时，更新购物车数量
						const targetCount = currentCount - 1;
						const res = await updateCart({
							goodsId: goodsId,
							count: targetCount,
							storeId: this.storeId
						});

						if ([200, 0].includes(res.code)) {
							this.$set(this.localCartMap[goodsId], 'count', targetCount);
						} else {
							throw new Error(res.msg || '更新购物车数量失败');
						}
					}

					// 触发购物车数量变化事件
					uni.$emit('cartCountChange');

				} catch (e) {
					console.error('减少购物车数量失败：', e);
					uni.showToast({
						title: e.message || '操作失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			// 同步购物车状态（用于页面间同步）
			syncCartStatus() {
				// 这里可以根据实际需求从后端重新获取购物车数据，保持状态一致
				// 简化实现：可以留空，或添加重新获取逻辑
			},
			goToCart() {
				if (this.totalCartCount === 0) {
					uni.showToast({
						title: '购物车是空的哦',
						icon: 'none'
					});
					return;
				}
				uni.switchTab({
					url: '/pages/cart/cart',
					fail: (err) => {
						console.error('跳转购物车失败:', err);
						uni.showToast({
							title: '购物车页面不存在',
							icon: 'none'
						});
					}
				});
			},
			goToGoodsDetail(goods) {
				if (!goods?.goodsId) return;

				if (goods.isOnSale === 0) {
					uni.showToast({
						title: '商品已下架',
						icon: 'none',
						duration: 1500
					});
					return;
				}

				uni.navigateTo({
					url: `/pages/goods/goodsDetail?goodsId=${goods.goodsId}`,
					fail: (err) => {
						console.error('跳转商品详情失败:', err);
						uni.showToast({
							title: '商品详情页不存在',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style scoped>
	/* 基础样式重置 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.store-detail-page {
		min-height: 100vh;
		background-color: #fff8f5;
	}

	/* 图标通用样式 */
	.iconfont {
		font-size: inherit;
		color: inherit;
	}

	/* 店铺头部 */
	.store-header {
		background-color: #fff;
		padding: 12px 16px;
		display: flex;
		gap: 12px;
		align-items: center;
		border-bottom: 1px solid #fee9e1;
	}

	.back-icon {
		font-size: 20px;
		color: #2d3748;
		cursor: pointer;
	}

	.store-header-img {
		width: 80px;
		height: 80px;
		border-radius: 8px;
		object-fit: cover;
	}

	.store-header-info {
		flex: 1;
	}

	.store-header-name {
		font-size: 16px;
		font-weight: 600;
		color: #2d3748;
		margin-bottom: 6px;
		display: block;
	}

	.store-header-meta {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 12px;
		font-size: 13px;
		color: #718096;
		margin-bottom: 4px;
	}

	.star-icon {
		color: #FFD166;
		margin-right: 2px;
	}

	.storeStatus-badge {
		font-size: 12px;
		padding: 2px 6px;
		border-radius: 4px;
		color: #fff;
		width: fit-content;
	}

	.storeStatus-badge.open {
		background-color: rgba(0, 180, 42, 0.8);
	}

	.storeStatus-badge.close {
		background-color: rgba(153, 153, 153, 0.8);
	}

	/* 搜索栏 */
	.search-box {
		position: relative;
		height: 38px;
		background-color: #fff5f0;
		border-radius: 20px;
		padding: 0 16px;
		display: flex;
		align-items: center;
		margin: 12px 16px;
	}

	.search-icon {
		font-size: 16px;
		color: #999;
	}

	.search-input {
		flex: 1;
		height: 100%;
		background: transparent;
		font-size: 14px;
		color: #4a5568;
		padding-left: 8px;
		border: none;
		outline: none;
	}

	.clear-icon {
		position: absolute;
		right: 16px;
		cursor: pointer;
		font-size: 16px;
		color: #999;
	}

	/* 筛选栏 */
	.filter-bar {
		display: flex;
		background-color: #fff;
		padding: 12px 16px;
		border-bottom: 1px solid #fee9e1;
	}

	.filter-item {
		display: flex;
		align-items: center;
		gap: 6px;
		color: #4a5568;
		font-size: 14px;
		margin-right: 24px;
		cursor: pointer;
	}

	/* 加载中样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40px 0;
	}

	.loading-spinner {
		width: 24px;
		height: 24px;
		border: 3px solid #ff7a45;
		border-top-color: transparent;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 14px;
		color: #718096;
		margin-top: 12px;
	}

	/* 商品列表 */
	.goods-list {
		padding: 12px 16px;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 12px;
	}

	.goods-card {
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		position: relative;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
	}

	.goods-offline {
		opacity: 0.6;
	}

	.goods-img {
		width: 100%;
		height: 120px;
		object-fit: cover;
	}

	.offline-tag {
		position: absolute;
		top: 8px;
		left: 8px;
		background-color: #999;
		color: #fff;
		font-size: 12px;
		padding: 2px 6px;
		border-radius: 4px;
		z-index: 1;
	}

	/* 商品信息 */
	.goods-info {
		padding: 10px;
	}

	.goods-name-wrap {
		margin-bottom: 6px;
	}

	.goods-name {
		font-size: 14px;
		color: #2d3748;
		line-height: 1.3;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.goods-middle-wrap {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 6px;
	}

	.goods-spec {
		font-size: 12px;
		color: #718096;
	}

	.cart-operation {
		display: flex;
		align-items: center;
		gap: 4px;
	}

	.minus-icon {
		font-size: 18px;
		color: #ff7a45;
		width: 24px;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #ff7a45;
		border-radius: 4px;
		cursor: pointer;
	}

	.count {
		font-size: 14px;
		color: #2d3748;
		min-width: 18px;
		text-align: center;
	}

	.add-btn {
		width: 24px;
		height: 24px;
		border-radius: 4px;
		background-color: #ff7a45;
		color: #fff;
		font-size: 18px;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
		line-height: 24px;
		border: none;
	}

	.minus-icon.disabled {
		opacity: 0.4;
		pointer-events: none;
		border-color: #ffc1a8;
		color: #ffc1a8;
	}

	.goods-price-wrap {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.goods-price {
		font-size: 15px;
		font-weight: 600;
		color: #e53e3e;
	}

	.goods-sales {
		font-size: 12px;
		color: #718096;
	}

	/* 错误提示 */
	.error-container {
		background-color: #fff5f5;
		border-radius: 10px;
		padding: 14px;
		margin: 12px;
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.error-icon {
		font-size: 20px;
		color: #f53f3f;
	}

	.error-text {
		color: #e53e3e;
		font-size: 14px;
		flex: 1;
	}

	.retry-btn {
		background-color: #ff7a45;
		color: #fff;
		padding: 6px 14px;
		border-radius: 6px;
		font-size: 14px;
		border: none;
	}

	/* 无数据状态 */
	.no-data {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60px 0 40px;
	}

	.empty-icon {
		font-size: 60px;
		color: #ffe0d0;
	}

	.no-data-text {
		color: #a0aec0;
		font-size: 15px;
		margin-top: 16px;
	}

	.no-data-subtext {
		color: #cbd5e0;
		font-size: 13px;
		margin-top: 8px;
	}

	/* 清除button默认样式 */
	button::after {
		border: none;
	}

	/* 购物车入口样式 */
	.cart-entrance {
		position: relative;
		margin-left: auto;
		font-size: 24px;
		color: #ff7a45;
		cursor: pointer;
	}

	.cart-count {
		position: absolute;
		top: -5px;
		right: -5px;
		width: 18px;
		height: 18px;
		border-radius: 50%;
		background-color: #f53f3f;
		color: white;
		font-size: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>